﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using LN = Lucene.Net;

namespace CYTS.Aoyou.LuceneSearch
{
    public class DocManager
    {
        /// <summary>
        /// 从数据库中获取新的文档
        /// </summary>
        /// <param name="topCount"></param>
        /// <returns></returns>
        public static List<Doc> GetFreshDocs(int topCount)
        {
            List<Doc> list = new List<Doc>();
            DataSet ds = DataAccess.GetDataSetBySP("usp_search_getlist", new []{ new SqlParameter("@topnum", topCount) });
            if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
            {
                var dt = ds.Tables[0].AsEnumerable();
                foreach (DataRow dr in dt)
                {
                    Doc doc = ConvertDataRowToDoc(dr);
                    list.Add(doc);
                }
            }

            return list;
        }

        /// <summary>
        /// 从数据库中获取过期的文档
        /// </summary>
        /// <returns></returns>
        public static List<Doc> GetObsoleteDocs()
        {
            List<Doc> list = new List<Doc>();
            DataSet ds = DataAccess.GetDataSetBySP("usp_search_getdellist");
            if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
            {
                var dt = ds.Tables[0].AsEnumerable();
                foreach (DataRow dr in dt)
                {
                    Doc doc = ConvertDataRowToDoc(dr);
                    list.Add(doc);
                }
            }

            return list;
        }

        /// <summary>
        /// 更新数据库文档标志位
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id"></param>
        public static void UpdateDocsStatus(string type, int id)
        {
            DataAccess.ExecuteSP("usp_search_update", new[] { new SqlParameter("@s_type", type), new SqlParameter("@s_id", id) });
        }

        /// <summary>
        /// 把数据库字段赋值给类的属性
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private static Doc ConvertDataRowToDoc(DataRow dr)
        {
            Doc doc = new Doc();
            doc.Abstract = string.Empty;
            doc.Content = dr.Field<string>("f_content");
            doc.Date = dr.Field<DateTime>("f_createtime");
            doc.ReplyCount = dr.Field<int>("f_replynum");
            doc.Keywords = string.Empty;
            doc.Region = dr.Field<string>("f_ptitle");
            doc.Source = dr.Field<string>("f_source");
            doc.Title = dr.Field<string>("f_title");
            doc.ViewCount = dr.Field<int>("f_viewnum");
            doc.Type = dr.Field<string>("s_type");
            doc.Id = dr.Field<int>("f_id");
            doc.Uid = doc.Type + doc.Id;
            return doc;
        }
    }
}
